<template>
    <view>
        <!-- pages/user/ucenter/index.wxml -->
        <text>用户个人中心</text>
        <view>
            <text>用户信息：</text>
            <text>{{ nickName }}</text>
        </view>
        <view>
            <text>绑定用户信息：</text>
            <text>{{ bindUser }}</text>
        </view>
        <button style="margin-top: 20px" type="primary" v-if="!userId" @tap="bind">绑定用户</button>
        <button style="margin-top: 20px" type="danger" v-if="userId" @tap="unbind">解绑用户</button>
    </view>
</template>

<script>
// pages/user/ucenter/index.js
const app = getApp();
const JBolt = app.globalData.getJBolt();
export default {
    data() {
        return {
            userId: null,
            nickName: '昵称',
            bindUser: '未绑定'
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        JBolt.log('ucenter onload');
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.readData();
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        readData: function () {
            var that = this;
            JBolt.apiGet({
                url: JBolt.API.wechat.user.me
            }).then((data) => {
                var bindUser = data.data.bindUser;
                var userId = null;

                if (bindUser) {
                    var bs = bindUser.split(',');
                    userId = bs[0].split('_')[1];
                }

                that.setData({
                    nickName: data.data.nickname,
                    bindUser: bindUser,
                    userId: userId
                });
            });
        },

        unbind: function () {
            var that = this;
            var userId = this.userId;

            if (userId) {
                JBolt.apiPost({
                    url: JBolt.API.wechat.unbindOtherUser,
                    data: {
                        type: JBolt.API.wechat.bindUserType.SYSTEM_USER,
                        userId
                    }
                }).then(() => {
                    JBolt.log('unbind success');
                    that.readData();
                });
            } else {
                JBolt.MsgBox.alert('未绑定任何用户');
            }
        },

        bind: function () {
            JBolt.openPage('/pages/jbolt/user/bind/index');
        }
    }
};
</script>
<style>
@import './index.css';
</style>
